﻿/**********************************************************************
	minidump.cpp
	程序意外关闭生成dump文件实现
**********************************************************************/
#ifdef _MSC_VER

#pragma warning(disable:4091)

#include "MiniDump.h"

#include <stdio.h>
#include <stdlib.h>
#include <Dbghelp.h>
#include <shlwapi.h>

#pragma comment( lib, "DbgHelp" )
#pragma comment( lib, "shlwapi.lib" )

//---------------------------------------------------------------------
LONG WINAPI MyUnhandledExceptionFilter(struct _EXCEPTION_POINTERS* ExceptionInfo)
{
	CHAR szCrashFile[MAX_PATH] = {0};
	SYSTEMTIME timeNow;
	::GetLocalTime(&timeNow);
	_snprintf(szCrashFile, MAX_PATH, "%s_crash_%04d%02d%02d%02d%02d%02d.dmp", 
		g_dump_exe_name, timeNow.wYear, timeNow.wMonth, timeNow.wDay, timeNow.wHour, timeNow.wMinute,timeNow.wSecond );

	HANDLE lhDumpFile = CreateFileA(szCrashFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL ,NULL);
	if(lhDumpFile)
	{
		MINIDUMP_EXCEPTION_INFORMATION loExceptionInfo;
		loExceptionInfo.ExceptionPointers = ExceptionInfo;
		loExceptionInfo.ThreadId = GetCurrentThreadId();
		loExceptionInfo.ClientPointers = TRUE;

		int MiniDumpWithDataSegs = MiniDumpNormal |
			MiniDumpWithHandleData |
			MiniDumpWithUnloadedModules |
			MiniDumpWithIndirectlyReferencedMemory |   
			MiniDumpScanMemory |
			MiniDumpWithProcessThreadData |
			MiniDumpWithThreadInfo; 
		MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),lhDumpFile, (MINIDUMP_TYPE)MiniDumpWithDataSegs, &loExceptionInfo, NULL, NULL);
		CloseHandle(lhDumpFile);
	}

	return EXCEPTION_EXECUTE_HANDLER;
}

#pragma warning(default: 4091)

#endif //_MSC_VER